package monitor;
import java.util.*;
import org.omg.CORBA.*;
import org.omg.CosNaming.*;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;

import lagern.*;

/**
 * Monitor class
 * @author Laurine and Vincent
 *
 */
public class Monitor {
	
	private static Lager LagerRef;
	private static ORB orb;
	
	public static void main(String[] args) {
			try {
			//args[0] = host
			//args[1] = port
			Integer.parseInt(args[1]); //to check if the port is an Integer. If not, an NumberFormatException is thrown
			//orb configuration
			Properties props = new Properties();
			props.put("org.omg.CORBA.ORBInitialPort", args[1]);
			props.put("org.omg.CORBA.ORBInitialHost", args[0]);
			//orb initialization
			orb = ORB.init(args, props);
			System.out.println("ORB initialisiert ...");
			
			//get the NamingContext	
			NamingContextExt nc = NamingContextExtHelper.narrow(
					orb.resolve_initial_references("NameService"));
			
			//Get the reference from the name "Lager"
            LagerRef = LagerHelper.narrow(
                    nc.resolve_str("lager"));
            
          //get the reference of rootPOA and activate POA Manager
			POA rootPoa =
					POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
			rootPoa.the_POAManager().activate();
			
			//Creation of the servant
			MonitorImpl Monitor = new MonitorImpl();
			rootPoa.activate_object(Monitor);
			
			//get the object reference of Monitor
			org.omg.CORBA.Object ref = rootPoa.servant_to_reference(Monitor);
            
			lagern.Monitor MonitorRef = MonitorHelper.narrow(ref);
			
			// get the root naming context
	        org.omg.CORBA.Object objRef =
	        orb.resolve_initial_references("NameService");
	        //Use NamingContextExt instead of NamingContext. This is
	        // part of the Interoperable naming Service.
	        NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
			
			//bind the reference of "monitor" with the name "Monitor"
			ncRef.rebind(ncRef.to_name("monitor"), MonitorRef);
            
			//activate monitor on the server
			LagerRef.aktiviereMonitor(MonitorRef);
			
			
			//start the orb and waiting for messages
            orb.run();
            
            
			}catch(NumberFormatException e){
				System.err.println("Please check the port");
				System.exit(1);
			}catch (Exception ex) {
				System.err.println("Problem with the connexion. Please check the parameters.");
				System.err.println("<Corba NameService host> <Corba NameService port>");
				System.exit(1);
			}			
			
	}
}

